package cn.zn.modules.appoin.service.impl;

import cn.zn.modules.appoin.dao.AtrWeekDao;
import cn.zn.modules.appoin.entity.AtrWeekEntity;
import cn.zn.modules.appoin.entity.AtrWeekWorkTimeEntity;
import cn.zn.modules.appoin.service.AtrWeekService;
import cn.zn.modules.appoin.service.AtrWeekWorkTimeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

@Service
public class AtrWeekServiceImpl extends ServiceImpl<AtrWeekDao, AtrWeekEntity> implements AtrWeekService {

    @Autowired
    AtrWeekWorkTimeService atrWeekWorkTimeService;

    @Override
    public void saveWeek(String ruleId) {
        String[] timeStrs = new String[]{
                "08:30-11:30",
                "14:30-17:00"
        };
        Integer[] weekDays = {Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY};
        AtrWeekEntity atrWeekEntity;
        for (int i = 0; i < weekDays.length; i++) {
            atrWeekEntity = AtrWeekEntity.builder()
                    .ruleId(ruleId)
                    .weekDay(weekDays[i])
                    .isWork(i < 5)
                    .build();
            atrWeekEntity.setSortNum(i);
            this.save(atrWeekEntity);
            if (atrWeekEntity.getIsWork()) {
                // 保存工作时间
                for (String timeStr : timeStrs) {
                    String[] times = timeStr.split("-");
                    atrWeekWorkTimeService.save(AtrWeekWorkTimeEntity.builder()
                            .weekId(atrWeekEntity.getId())
                            .startTime(times[0])
                            .endTime(times[1])
                            .build());
                }
            }
        }
    }

    @Override
    public void updateWeek(AtrWeekEntity atrWeekEntity) {
        super.updateById(atrWeekEntity);
        // 删除工作时间
        atrWeekWorkTimeService.remove(new QueryWrapper<AtrWeekWorkTimeEntity>().eq("WEEK_ID_", atrWeekEntity.getId()));
        // 保存工作时间
        if (atrWeekEntity.getWeekWorkTimes() != null) {
            atrWeekEntity.getWeekWorkTimes().forEach(o -> {
                o.setWeekId(atrWeekEntity.getId());
                atrWeekWorkTimeService.save(o);
            });
        }
    }

    @Override
    public AtrWeekEntity queryByWeekday(String ruleId, int weekDay) {
        return this.baseMapper.queryByWeekday(ruleId, weekDay);
    }
}
